<script setup>
import { ref, computed, watch, reactive } from 'vue'
import MediaItem from './MediaItem.vue'
import { ElMessage } from 'element-plus'
import VideoPlayer from './VideoPlayer.vue'

const props = defineProps({
  folderPath: {
    type: String,
    default: ''
  },
  selectedFiles: {
    type: Array,
    required: true,
    default: () => []
  },
  movedFiles: {
    type: Boolean,
    default: false
  },
  targetFolder: {
    type: String,
    default: ''
  },
  selectedTargetPath: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['selection-change', 'target-select', 'target-path-select', 'move-files'])

// 状态管理
const state = reactive({
  mediaFiles: [],
  loading: false,
  currentPage: 1,
  gridSize: 'medium',
  lastSelected: null
})

const PAGE_SIZE = 50

// 网格布局样式
const gridStyle = computed(() => ({
  display: 'grid',
  gridTemplateColumns: state.gridSize === 'large' 
    ? 'repeat(3, minmax(0, 1fr))'
    : state.gridSize === 'small'
      ? 'repeat(6, minmax(0, 1fr))'
      : 'repeat(4, minmax(0, 1fr))',
  gap: state.gridSize === 'large' ? '16px' : state.gridSize === 'small' ? '8px' : '12px',
  padding: state.gridSize === 'large' ? '16px 10px' : state.gridSize === 'small' ? '12px' : '14px'
}))

// 加载媒体文件
const loadFiles = async (reset = false) => {
  if (!props.folderPath || state.loading) return
  
  if (reset) {
    state.currentPage = 1
    state.mediaFiles = []
    state.lastSelected = null
  }

  state.loading = true
  try {
    const result = await window.mediaManager.readMediaFiles(
      props.folderPath,
      state.currentPage,
      PAGE_SIZE
    )
    
    state.mediaFiles = reset ? result.files : [...state.mediaFiles, ...result.files]
    state.currentPage++
  } catch (error) {
    console.error('Load files failed:', error)
    ElMessage.error('加载文件失败')
  } finally {
    state.loading = false
  }
}

// 处理文件点击
const handleFileClick = (event, file) => {
  const newSelection = [...props.selectedFiles]
  const index = newSelection.indexOf(file.path)

  if (event.shiftKey && state.lastSelected) {
    const currentIndex = state.mediaFiles.findIndex(f => f.path === file.path)
    const lastIndex = state.mediaFiles.findIndex(f => f.path === state.lastSelected)
    
    if (lastIndex !== -1) {
      const start = Math.min(lastIndex, currentIndex)
      const end = Math.max(lastIndex, currentIndex)
      
      for (let i = start; i <= end; i++) {
        const path = state.mediaFiles[i].path
        if (!newSelection.includes(path)) {
          newSelection.push(path)
        }
      }
    }
  } else {
    if (index === -1) {
      newSelection.push(file.path)
    } else {
      newSelection.splice(index, 1)
    }
  }

  state.lastSelected = file.path
  emit('selection-change', newSelection)
}

// 清除缓存
const clearCache = async () => {
  if (state.loading) return
  
  state.loading = true
  try {
    await window.mediaManager.clearThumbnails()
    ElMessage.success('缓存清除成功')
    loadFiles(true)
  } catch (error) {
    console.error('Clear cache failed:', error)
    ElMessage.error('缓存清除失败')
  } finally {
    state.loading = false
  }
}

// 移除已移动的文件
const removeFiles = (filePaths) => {
  if (!filePaths || filePaths.length === 0) return
  
  state.mediaFiles = state.mediaFiles.filter(file => !filePaths.includes(file.path))
}

// 添加新的方法来处理文件移动
const handleFilesMove = () => {
  if (props.selectedFiles.length === 0) return
  
  // 创建要移动的文件路径集合
  const movedPaths = new Set(props.selectedFiles)
  
  // 直接更新媒体文件列表，移除已移动的文件
  state.mediaFiles = state.mediaFiles.filter(file => !movedPaths.has(file.path))
  
  // 触发选择变更事件，清空选择
  emit('selection-change', [])
}

// 监听文件移动事件
watch(
  () => props.movedFiles,
  (newValue, oldValue) => {
    if (newValue === true && oldValue === false) {
      handleFilesMove()
    }
  }
)

// 监听文件夹变化
watch(() => props.folderPath, (newPath) => {
  if (newPath) {
    loadFiles(true)
  }
}, { immediate: true })

// 处理滚动加载
const containerRef = ref(null)
const handleScroll = (e) => {
  const { scrollTop, clientHeight, scrollHeight } = e.target
  if (scrollHeight - scrollTop - clientHeight < 200) {
    loadFiles()
  }
}

// 视频播放相关
const videoDialogVisible = ref(false)
const currentVideoFile = ref(null)

// 处理视频播放
const handleVideoPlay = (file) => {
  currentVideoFile.value = file
  videoDialogVisible.value = true
}

// 将 handleVideoPlay 传递给 MediaItem
const handleMediaItemEvent = (type, data) => {
  if (type === 'play-video') {
    handleVideoPlay(data)
  }
}

// 处理视频切换
const handleVideoChange = (file) => {
  if (file) {
    currentVideoFile.value = file
    videoDialogVisible.value = true  // 确保对话框保持打开状态
  }
}

// 处理视频移动
const handleVideoMove = async (file) => {
  try {
    // 使用与主界面相同的移动逻辑
    emit('selection-change', [file.path])
    await emit('move-files')
    
    // 从媒体文件列表中移除已移动的文件
    state.mediaFiles = state.mediaFiles.filter(f => f.path !== file.path)
  } catch (error) {
    console.error('Move video failed:', error)
    ElMessage.error('移动失败')
  }
}
</script>

<template>
  <div 
    class="media-grid-container" 
    ref="containerRef" 
    @scroll="handleScroll"
  >
    <!-- 工具栏 -->
    <div class="grid-toolbar" v-if="state.mediaFiles.length > 0">
      <div class="toolbar-left">
        <el-radio-group v-model="state.gridSize" size="small">
          <el-radio-button label="small">小图</el-radio-button>
          <el-radio-button label="medium">中图</el-radio-button>
          <el-radio-button label="large">大图</el-radio-button>
        </el-radio-group>
        <span class="sort-info">按修改时间排序</span>
        <el-button 
          size="small" 
          type="info" 
          :loading="state.loading"
          @click="clearCache"
        >
          <template #icon>
            <el-icon><Delete /></el-icon>
          </template>
          清除预览图缓存
        </el-button>
        <el-button 
          size="small" 
          type="primary" 
          @click="loadFiles(true)"
        >
          <template #icon>
            <el-icon><Refresh /></el-icon>
          </template>
          刷新
        </el-button>
      </div>
      <div class="selection-controls" v-if="selectedFiles.length > 0">
        <span class="selection-info">
          已选择 {{ selectedFiles.length }} 个文件
        </span>
        <el-button 
          size="small"
          type="default"
          @click="emit('selection-change', [])"
        >
          <template #icon>
            <el-icon><Close /></el-icon>
          </template>
          取消选择
        </el-button>
      </div>
    </div>

    <!-- 媒体网格 -->
    <div 
      class="media-grid" 
      :style="gridStyle"
      :class="{ 'large-grid': state.gridSize === 'large' }"
    >
      <MediaItem
        v-for="file in state.mediaFiles"
        :key="file.path"
        :file="file"
        :selected="selectedFiles.includes(file.path)"
        @click="(e) => handleFileClick(e, file)"
        @media-event="handleMediaItemEvent"
      />
    </div>

    <!-- 视频播放器 -->
    <VideoPlayer
      v-model:visible="videoDialogVisible"
      :file="currentVideoFile"
      :media-files="state.mediaFiles.filter(f => f.type === 'video')"
      :target-folder="targetFolder"
      :selected-target-path="selectedTargetPath"
      @target-select="$emit('target-select', $event)"
      @target-path-select="$emit('target-path-select', $event)"
      @file-change="handleVideoChange"
      @move-file="handleVideoMove"
    />

    <!-- 加载状态 -->
    <div v-if="state.loading" class="loading-more">
      <el-icon class="loading"><Loading /></el-icon>
      加载中...
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="!state.loading && state.mediaFiles.length === 0"
      description="没有媒体文件"
    />
  </div>
</template>

<style scoped>
.media-grid-container {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  width: 100%;
}

.grid-toolbar {
  position: sticky;
  top: 0;
  z-index: 1;
  background: white;
  padding: 10px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.selection-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selection-info {
  color: var(--el-color-primary);
  font-size: 14px;
}

.media-grid {
  flex: 1;
  min-height: 0;
  width: 100%;
  box-sizing: border-box;
  user-select: none;
}

.loading-more {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 大图模式特殊样式 */
.large-grid {
  padding: 0 4px;
}

.large-grid :deep(.media-item) {
  aspect-ratio: unset;
  height: auto;
}

.large-grid :deep(.media-preview-container) {
  padding-top: 0;
  height: auto;
  min-height: 500px;
  max-height: 900px;
}

.large-grid :deep(.media-preview) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #f5f7fa;
}

.large-grid :deep(.thumbnail-container) {
  height: 700px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 8px;
  overflow: hidden;
}

.large-grid :deep(.video-thumbnail) {
  height: 700px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
}

/* 响应式调整 */
@media screen and (max-width: 1600px) {
  .media-grid[style*="repeat(6, minmax"] {
    grid-template-columns: repeat(5, minmax(0, 1fr)) !important;
  }
}

@media screen and (max-width: 1400px) {
  .media-grid[style*="repeat(6, minmax"] {
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
  }
  .media-grid[style*="repeat(4, minmax"] {
    grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
  }
}

@media screen and (max-width: 1200px) {
  .media-grid[style*="repeat(6, minmax"] {
    grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
  }
  .media-grid[style*="repeat(4, minmax"] {
    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
  }
  .media-grid[style*="repeat(2, minmax"] {
    grid-template-columns: repeat(1, minmax(0, 1fr)) !important;
  }
}

@media screen and (max-width: 768px) {
  .grid-toolbar {
    padding: 8px 16px;
  }
  
  .media-grid {
    width: calc(100% - 32px);
  }

  .media-grid[style*="repeat"] {
    grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
  }

  .large-grid {
    padding: 0 16px;
  }

  .toolbar-left {
    flex-wrap: wrap;
    gap: 8px;
  }

  .sort-info {
    display: none;
  }

  .selection-controls {
    gap: 8px;
  }

  .selection-info {
    font-size: 13px;
  }
}

@media screen and (max-width: 480px) {
  .media-grid[style*="repeat"] {
    grid-template-columns: repeat(1, minmax(0, 1fr)) !important;
  }
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sort-info {
  color: #909399;
  font-size: 13px;
}

.media-item {
  cursor: pointer;
}
</style> 